package com.tg.paw.ums.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tg.paw.common.annotation.LoginAdmin;
import com.tg.paw.common.constant.CommonConstant;
import com.tg.paw.common.entity.UserAdmin;
import com.tg.paw.common.util.CommonPageResult;
import com.tg.paw.common.util.CommonResult;
import com.tg.paw.common.util.QueryUtil;
import com.tg.paw.ums.entity.Role;
import com.tg.paw.ums.entity.RolePermissionRelation;
import com.tg.paw.ums.params.RolePermissionParams;
import com.tg.paw.ums.service.IApiPermissionService;
import com.tg.paw.ums.service.IRolePermissionRelationService;
import com.tg.paw.ums.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author Rubble
 * @since 2020-10-22
 */
@RestController
@Slf4j
@Api(tags = "角色管理", value = "RoleController")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IApiPermissionService apiPermissionService;

    @Autowired
    private IRolePermissionRelationService rolePermissionRelationService;


    @ApiOperation("根据条件分页查询角色列表")
    @GetMapping(value = "/api/ums/role")
    public CommonResult getRoleByPage(Role entity,
                                    @RequestParam(value = "current", defaultValue = "1") Integer pageNo,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "sorter", defaultValue = "") String sorter,
                                    @RequestParam(value = "filter", defaultValue = "") String filter) {
        try {
            QueryUtil.writeEmptyString2Null(entity);
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>(entity);
            QueryUtil.buildQuery(queryWrapper,filter,sorter,Role.class);
            return CommonPageResult.pageResult(roleService.page(new Page<>(pageNo, pageSize), queryWrapper));
        } catch (Exception e) {
            log.error("根据条件查询所有角色：{}", e.getMessage(), e);
        }
        return CommonResult.failed();
    }

    @ApiOperation("保存角色表")
    @PostMapping(value = "/api/ums/role")
    public CommonResult saveRole(@RequestBody Role entity, @LoginAdmin(isFull = true) UserAdmin userAdmin) {
            try {
                if(userAdmin.getUserType()==1){
                    long parentId = userAdmin.getParentId()!=null?userAdmin.getParentId():userAdmin.getUserId();
                    entity.setOwner(parentId);
                }
                if (roleService.save(entity)) {
                    return CommonResult.success();
                }
            } catch (Exception e) {
                log.error("保存角色表：{}", e.getMessage(), e);
                return CommonResult.failed();
            }
            return CommonResult.failed();
    }

    @ApiOperation("更新角色")
    @PutMapping(value = "/api/ums/role/{id}")
    public CommonResult updateRole(@RequestBody Role entity,@ApiParam("角色id") @PathVariable Long id) {

        try {
            entity.setRoleId(id);
            if (roleService.updateById(entity)) {
                return CommonResult.success();
            }
        } catch (Exception e) {
            log.error("更新角色：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
        return CommonResult.failed();
    }

    @ApiOperation("删除角色")
    @DeleteMapping(value = "/api/ums/role/{id}")
    public CommonResult deleteRole(@ApiParam("角色id") @PathVariable Long id) {
        try {
            if (roleService.removeById(id)) {
                return CommonResult.success();
            }
        } catch (Exception e) {
            log.error("删除角色：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
        return CommonResult.failed();
    }

    @ApiOperation("查询角色")
    @GetMapping(value = "/api/ums/role/{id}")
    public CommonResult getRoleById(@ApiParam("角色id") @PathVariable Long id) {
        if(id == CommonConstant.ADMIN_ROLE_ID || id==CommonConstant.STORE_ADMIN_ROLE_ID){
            return CommonResult.failed("系统管理员、店铺管理员 不能删除");
        }
        try {
            Role coupon = roleService.getById(id);
            return CommonResult.success(coupon);
        } catch (Exception e) {
            log.error("查询角色：{}", e.getMessage(), e);
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "批量删除角色")
    @DeleteMapping(value = "/api/ums/role")
    public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) {
        ids = ids.stream().filter(id->(id!=CommonConstant.ADMIN_ROLE_ID &&id!=CommonConstant.STORE_ADMIN_ROLE_ID)).collect(Collectors.toList());
        boolean success = roleService.removeByIds(ids);
        return CommonResult.instance(success);
    }


    @ApiOperation(value = "更改角色权限")
    @PostMapping(value = "/api/ums/role/permissions/relation")
    public CommonResult updateRolePermission(@Valid @RequestBody RolePermissionParams params, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            return CommonResult.validateFailed(bindingResult);
        }
       return apiPermissionService.updateRolePermission(params);
    }

    @ApiOperation(value = "获取角色勾选的权限")
    @GetMapping(value = "/api/ums/role/permission/checkedItems")
    public CommonResult updateRolePermission(Long roleId) {
        LambdaQueryWrapper<RolePermissionRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermissionRelation::getRoleId,roleId);
        queryWrapper.eq(RolePermissionRelation::getImmediate,0);
        List<RolePermissionRelation> list = rolePermissionRelationService.list(queryWrapper);
        List<String> ids = list.stream().map(item -> item.getPermissionId().toString()).collect(Collectors.toList());

        return CommonResult.success(ids);
    }

}
